# -*- coding: utf-8 -*-
# @Author : Yuan
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, ListAPIView, DestroyAPIView
from rest_framework.mixins import ListModelMixin
from apps.meiduo_admin.serializers.serializers import SKUImageModelSerializer, SKUModelSerializer
from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.utils import PageNum
from rest_framework.viewsets import ModelViewSet
from rest_framework import status


class ImageView(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageModelSerializer
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        # 接收数据
        sku_id = request.data.get('sku')
        image_data = request.FILES.get('image')
        # 验证数据
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 上传图片
        from fdfs_client.client import Fdfs_client
        f_client = Fdfs_client('utils/fastdfs/client.conf')
        res = f_client.upload_by_buffer(image_data.read())
        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)
        # 保存数据
        image_url = res['Remote file_id']
        image_queryset = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 返回响应
        return Response({
            'id': image_queryset.id,
            'sku_id': sku_id,
            'image_url': image_queryset.image.url
        }, status=status.HTTP_201_CREATED)


class SKUView(APIView):
    def get(self, request):
        skus = SKU.objects.all()
        serializer = SKUModelSerializer(instance=skus, many=True)
        return Response(serializer.data)

# class SKUView(ListModelMixin, GenericAPIView):
#     queryset = SKU.objects.all()
#     serializer_class = SKUModelSerializer
#
#     def get(self, request):
#         return self.list(request)


# class SKUView(ListAPIView):
#     queryset = SKU.objects.all()
#     serializer_class = SKUModelSerializer



